#!/bin/bash

set -o pipefail
set -o errexit
set -o errtrace

export LC_ALL=C

BASE_ANN_DIR=$1
GENE_ID=$2

export BASE_DATE=$(head -n1 ${BASE_ANN_DIR}/base_date.txt)
export BASE_DATA_PATH=/tmp/mixagol/annotation_cluster

source 6_annotation/annotate_common.sh

ANNOTATE_DIRNAME=annot_$(date +%s.%N)
ANNOTATE_DIR=${BASE_DATA_PATH}/6_annotation/${ANNOTATE_DIRNAME}
mkdir -p $ANNOTATE_DIR

trap err_cleanup ERR

function err_cleanup() {
    echo 'Cleanup & exit..' >&2
    rm -rf $ANNOTATE_DIR
    exit 1
}

EXCL_GENOMES=$(head -n1 ${BASE_ANN_DIR}/excl_genomes.txt)

SIMUL_NW_FILE=$BASE_DATA_PATH/3_raw_matrix_nw/simulation/pupy/interpolation.txt
NORM_MATRIX_DIR=${BASE_DATA_PATH}/4_normed_matrix/${BASE_DATE}/wu_blast_nw_excl_${EXCL_GENOMES}
GENOMES_NUM=`cat "${NORM_MATRIX_DIR}/map_int_genom.txt" | wc -l`

read_and_prepare_input          $ANNOTATE_DIR   $GENE_ID
find_local_alignments_wu_blast  $ANNOTATE_DIR
find_global_alignments_nw_extra $ANNOTATE_DIR   $SIMUL_NW_FILE


for Z_VALUE in 5; do
    E_DIR=$ANNOTATE_DIR/e_$Z_VALUE
    mkdir -p $E_DIR

    create_vectors_nw      $ANNOTATE_DIR    $E_DIR    $Z_VALUE    $NORM_MATRIX_DIR   $EXCL_GENOMES
    find_sim_vectors_raw                    $E_DIR    $Z_VALUE    $NORM_MATRIX_DIR   $GENOMES_NUM
    find_sim_vectors                        $E_DIR    $Z_VALUE    $NORM_MATRIX_DIR
    #create_kegg_limited                     $E_DIR    $Z_VALUE    "1e-7"
    #create_gene_functions                   $E_DIR    $Z_VALUE
    #create_gene_functions_kegg              $E_DIR    $Z_VALUE
    #create_gene_functions_uniq              $E_DIR    $Z_VALUE
    #create_gene_functions_best_uniq         $E_DIR    $Z_VALUE
    #create_gene_functions_best_uniq_kegg    $E_DIR    $Z_VALUE
    create_gene_ontology                    $E_DIR    $Z_VALUE    "1e-6"
    clear_tmp_files                         $E_DIR
    #create_gene_pathways                    $E_DIR    $Z_VALUE
    #create_gene_pathways_avg_nw             $E_DIR    $Z_VALUE    $GENOMES_NUM

done

cp -r $ANNOTATE_DIR $BASE_ANN_DIR/.${ANNOTATE_DIRNAME}
rm -r $ANNOTATE_DIR
mv $BASE_ANN_DIR/.${ANNOTATE_DIRNAME} $BASE_ANN_DIR/${ANNOTATE_DIRNAME}

